//
//  HZEmoticonBottomView.swift
//  HansWeibo
//
//  Created by Hans on 16/8/18.
//  Copyright © 2016年 Hans. All rights reserved.
//

import UIKit

// 定义一个参数
private let tagNumber = 500

// 按钮枚举
enum HZEmoticonBottomViewType: Int {
    // 默认
    case Default = 0
    // emoji
    case Emoji = 1
    // 浪小花
    case Lxh = 2

}

// UIStackView 容器视图  ios9.0 以上可以使用
class HZEmoticonBottomView: UIStackView {
    // 记录当前选中的按钮
    var currentButton: UIButton?
    // 定义一个闭包
    var closure:((type:HZEmoticonBottomViewType)->())?
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //MARK: - 提供外界 调用
    func setupCurrentButton(tag:Int){
        // 得到button
        let button = viewWithTag(tag + tagNumber) as! UIButton
        selectButton(button)
        
    }
    
    //MARK: - 监听按钮方法
    func buttonClick(button: UIButton){
        
        selectButton(button)
        // 执行闭包
        closure?(type:HZEmoticonBottomViewType(rawValue: button.tag - tagNumber)!)
    }
    // 选中设置判断
    func selectButton(button: UIButton){
        // 如果当前选中的按钮和这次的相同 将不再设置
        if currentButton == button {
            return
        }
        
        // 取消上个选中按钮
        currentButton?.selected = false
        // 把当前按钮选中
        button.selected = true
        // 关联
        currentButton = button

    }
    
    //MARK: - 设置视图
    func setupUI(){

        // 填充方向
        axis = .Horizontal
        // 填充方式
        distribution = .FillEqually
        
        addChildButtons("left", title: "默认",type: .Default)
        addChildButtons("mid", title: "Emoji",type: .Emoji)
        addChildButtons("right", title: "浪小花",type: .Lxh)
        
        // 添加约束
    }
    
    // 创建按钮
    func addChildButtons(imageName:String,title:String,type:HZEmoticonBottomViewType){
        let button = UIButton()
        button.tag = type.rawValue + tagNumber
        // 添加事件
        button.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        button.setBackgroundImage(UIImage(named: "compose_emotion_table_\(imageName)_normal"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "compose_emotion_table_\(imageName)_selected"), forState: UIControlState.Selected)
        button.setTitle(title, forState: UIControlState.Normal)
        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Selected)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        // 默认情况下 default 是选中状态
        if type == .Default {
            button.selected = true
            currentButton = button
        }
        // 添加按钮
        addArrangedSubview(button)
    }
    
    
}
